#include <gtest/gtest.h>
#include "muxer_mp4_read.h"
#include "utils_log.h"
#include "utils_init.h"
#include "common_init.h"
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <thread>
#include "nlohmann/json.hpp"

namespace El {
namespace Muxer {

class MP4ReadTest : public ::testing::Test {
protected:
    static void SetUpTestSuite()
    {
        // 初始化基础库
        nlohmann::json config;
        config["log_level"] = "info";
        config["log_to_file"] = false;
        El::Utils::base_init(config);

        // 初始化配置
        config.clear();
        config["general"] = "/mnt/config/config";
        config["default"] = "/mnt/config/default";
        config["product"] = "/usr/etc/custom/product.yaml";
        El::Common::common_init(config);
    }

    void SetUp() override
    {
        reader_ = std::make_unique<MP4Read>();
        testFilePath_ = "/mnt/assets/video/h264_25_1M_aac_30.mp4";
    }

    void TearDown() override
    {
        reader_->Stop();
    }

    std::unique_ptr<MP4Read> reader_;
    std::string testFilePath_;
};

TEST_F(MP4ReadTest, VideoCallbackTest)
{
    ASSERT_TRUE(reader_->Open(testFilePath_));

    std::atomic<int> frameCount{0};
    std::condition_variable cv;
    std::mutex mtx;
    bool finished = false;

    auto callback = [&](const Media::MediaFramePtr &frame) {
        EL_INFO("视频帧信息: PTS={}, 大小={}字节", frame->GetPts(), frame->GetLength());
        frameCount++;
        if (frameCount >= 100) {
            std::lock_guard<std::mutex> lock(mtx);
            finished = true;
            cv.notify_one();
        }
    };

    EXPECT_TRUE(reader_->RegisterVideoCallback(callback));
    EXPECT_TRUE(reader_->Start());

    // Wait for frames or timeout
    {
        std::unique_lock<std::mutex> lock(mtx);
        EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(10), [&] { return finished; }));
    }

    EXPECT_GE(frameCount, 100);
}

TEST_F(MP4ReadTest, AudioCallbackTest)
{
    ASSERT_TRUE(reader_->Open(testFilePath_));

    std::atomic<int> frameCount{0};
    std::condition_variable cv;
    std::mutex mtx;
    bool finished = false;

    auto callback = [&](const Media::MediaFramePtr &frame) {
        EL_INFO("音频帧信息: PTS={}, 大小={}字节", frame->GetPts(), frame->GetLength());
        frameCount++;
        if (frameCount >= 20) {
            std::lock_guard<std::mutex> lock(mtx);
            finished = true;
            cv.notify_one();
        }
    };

    EXPECT_TRUE(reader_->RegisterAudioCallback(callback));
    EXPECT_TRUE(reader_->Start());

    // Wait for frames or timeout
    {
        std::unique_lock<std::mutex> lock(mtx);
        EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(10), [&] { return finished; }));
    }

    EXPECT_GE(frameCount, 20);
}

} // namespace Muxer
} // namespace El
